package cn.qu.phizline.webserver.event;

import cn.qu.phizline.event.Body;
import cn.qu.phizline.event.PayloadConventer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by zh on 2017/10/25.
 */
public class WebPayloadConventer extends PayloadConventer {

    private static final Logger logger = LoggerFactory.getLogger(WebPayloadConventer.class);

    @Override
    protected byte[] toPayloadBytes(Body body) {
        ObjectMapper mapper = new ObjectMapper();
        byte[] bodys = null;

        try {
            bodys = mapper.writeValueAsBytes(body);
        } catch (JsonProcessingException e) {
            logger.error("构建数据失败", e);
            return null;
        }
        return bodys;
    }

    @Override
    protected Body parsePayloadBody(Class<? extends Body> bodyClazz, byte[] bytes) {
        ObjectMapper mapper = new ObjectMapper();
        Body body = null;
        try {
            body = mapper.readValue(bytes, bodyClazz);
        } catch (IOException e) {
            logger.error("解析数据失败", e);
        }
        return body;
    }
}
